/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.fd.service.impl;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.xy.biz.fd.domain.bo.DocumentBO;
import com.xy.biz.fd.domain.bo.DocumentFavoriteBO;
import com.xy.biz.fd.domain.bo.RepositoryBO;
import com.xy.biz.fd.domain.query.DocumentFavoriteQuery;
import com.xy.biz.fd.domain.req.documentHistory.GetDocumentHistoryRequest;
import com.xy.biz.fd.manager.DocumentManager;
import com.xy.lang.util.CalendarUtils;
import com.xy.tool.context.UserContextHolder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xy.lang.domain.Result;
import com.xy.biz.fd.domain.bo.DocumentHistoryBO;
import com.xy.biz.fd.domain.query.DocumentHistoryQuery;
import com.xy.biz.fd.service.DocumentHistoryService;
import com.xy.biz.fd.manager.DocumentHistoryManager;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;

/**
 * @author wcs
 * @date 2021-2-3
 */
@Service
public class DocumentHistoryServiceImpl implements DocumentHistoryService, InitializingBean {

    @Autowired
    private DocumentHistoryManager documentHistoryManager;
    @Autowired
    private DocumentManager documentManager;
    @Autowired
    private DocumentEventBus documentEventBus;


    //新增访问记录
    @Override
    public void saveDocumentHistory(String minioStoragePath, Integer accessType, LocalDateTime now) {
//		DocumentHistoryBO documentHistory = documentHistoryManager.getDocumentHistory(documentHistoryBO);
//		if (documentHistory != null){ //判断之前是否访问过或者是否删除
//			if (documentHistory.getAccessType() == documentHistoryBO.getAccessType()){ //判断访问类型和上次是否一样
//				//一样就修改访问时间
//				documentHistory.setAccessTime(LocalDateTime.now());
//				int affectedRows = documentHistoryManager.updateDocumentHistory(documentHistory);
//				if (affectedRows > 0) {
//					return Result.success();
//				}
//				return Result.ofErrorRowsAffected();
//			}else { //不一样就修改访问时间和访问类型
//				documentHistory.setAccessTime(LocalDateTime.now());
//				documentHistory.setAccessType(documentHistoryBO.getAccessType());
//				int affectedRows = documentHistoryManager.updateDocumentHistory(documentHistory);
//				if (affectedRows > 0) {
//					return Result.success();
//				}
//				return Result.ofErrorRowsAffected();
//			}
//		}
        DocumentBO documentB0 = documentManager.getDocumentPath(minioStoragePath);

        DocumentHistoryBO documentHistoryBO = new DocumentHistoryBO();
        documentHistoryBO.setDocumentId(documentB0.getDocumentId());
        documentHistoryBO.setDocumentName(documentB0.getDocumentName());
        documentHistoryBO.setAccessType(accessType);
        documentHistoryBO.setAccessTime(now);
        documentHistoryBO.setCreateUserId(UserContextHolder.getUserId());
        documentHistoryBO.setCreateTime(now);
        documentHistoryBO.setDeleteFlag(false);

        int affectedRows = documentHistoryManager.saveDocumentHistory(documentHistoryBO);
        if (affectedRows > 0) {
            Result.success();
        }
        Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> saveAllDocumentHistory(Collection<DocumentHistoryBO> collection) {
        int affectedRows = documentHistoryManager.saveAllDocumentHistory(collection);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> updateDocumentHistory(DocumentHistoryBO documentHistoryBO) {
        int affectedRows = documentHistoryManager.updateDocumentHistory(documentHistoryBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    public Result<?> updateDocumentHistoriesByIds(Collection<Long> ids) {
        int affectedRows = documentHistoryManager.updateDocumentHistoriesByIds(ids);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> deleteDocumentHistory(Long documentHistoryId) {
        int affectedRows = documentHistoryManager.deleteDocumentHistory(documentHistoryId);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

	/*@Override
	public DocumentHistoryBO getDocumentHistory(Long documentHistoryId) {
		return documentHistoryManager.getDocumentHistory(documentHistoryId);
	}*/

    @Override
    public List<DocumentHistoryBO> listDocumentHistoryById(Collection<Long> collection) {
        return documentHistoryManager.listDocumentHistoryById(collection);
    }

    @Override
    public List<DocumentHistoryBO> listDocumentHistory(DocumentHistoryQuery query) {
        query.setCreateUserId(UserContextHolder.getUserId());
        //为文档浏览历史的文档添加文件扩展名
        List<DocumentHistoryBO> documentHistoryBOS = documentHistoryManager.listDocumentHistory(query);
        Set<Long> docIds = documentHistoryBOS.stream().map(DocumentHistoryBO::getDocumentId).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(docIds)) {
            return null;
        }
        //只将文档的扩展名作为value保存，后续需要其他属性可进行扩展
        Map<Long, String> docMap = documentManager.listDocumentById(docIds).stream().collect(Collectors.toMap(DocumentBO::getDocumentId, DocumentBO::getFileExtension));
        documentHistoryBOS = documentHistoryBOS.stream().peek(docHistory -> {
            docHistory.setFileExtension(docMap.get(docHistory.getDocumentId()));
            //上次访问时间（几分钟前）
            docHistory.setAccessTimeString(CalendarUtils.getDeadlineString(docHistory.getAccessTime(), LocalDateTime.now()));
        }).collect(Collectors.toList());
        return documentHistoryBOS;
    }

    @Override
    public int countDocumentHistory(DocumentHistoryQuery query) {
        query.setCreateUserId(UserContextHolder.getUserId());
        return documentHistoryManager.countDocumentHistory(query);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        documentEventBus.addDocumentStatusHandler((documentId) -> {
            List<DocumentHistoryBO> documentHistoryBOS = documentHistoryManager.listDocumentHistory(DocumentHistoryQuery.max().documentId(documentId).build());
            if (CollectionUtils.isEmpty(documentHistoryBOS)) {
                return;
            }
            Set<Long> ids = documentHistoryBOS.stream().map(DocumentHistoryBO::getDocumentHistoryId).collect(Collectors.toSet());
            documentHistoryManager.updateDocumentHistoriesByIds(ids);
        });
    }
}
